package dictionary;

import java.io.*;
import java.util.concurrent.BrokenBarrierException;
import javax.xml.crypto.Data;
import sun.font.TrueTypeFont;

public class DicDaoIo implements  DicDao {

    @Override
    public void save(MyDic myDic) {
        BufferedWriter bw=null;
        try {
            bw=new BufferedWriter(new FileWriter("d:\\d.txt",true));
            bw.write(myDic.getId()+"--"+myDic.getEnglish()+"--"+myDic.getChinese()+
            "--"+myDic.getComment());
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @Override
    public MyDic query(String name) {
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader("d:\\d.txt"));
            String line;
            while ((line=br.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void queryall() {
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader("D:\\d.txt"));
            String line=null;
            while ((line=br.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void delect(String name) {
      if (query(name)==null){
        System.out.println("要删除的内容不存在");
        return;
      }else{
        BufferedWriter bw=null;
        BufferedReader br=null;
        try {
          br=new BufferedReader(new FileReader("d:\\d.txt"));
          bw=new BufferedWriter(new FileWriter("d:\\new.txt",true));
          String line;
          while ((line=br.readLine())!=null){
            String[] date=line.split("--");
            Object[] data = new Object[0];
            if (!name.equals(data[1])){
              bw.write(line);
              bw.newLine();
              bw.flush();
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }

      }

    }
}
